import java.util.*;
import java.io.*;
import java.net.*;
/**
 * 
 * @author Jesse en Jeroen
 *
 */

public class Response extends HashMap<String, String> 
{	
	Socket c;
	byte[] body;
	
	public Response(Socket client)
	{
		this.c = client;
		this.put("Version", "HTTP/1.1");
		this.put("Server", "J&J Server 2007");
		
		Date time = Calendar.getInstance().getTime();
		String tijd = time.toString();
		System.out.println("testtijd " + tijd);
		String[] tijdstrings = tijd.split(" ");
		tijd = tijdstrings[0] + ", " + tijdstrings[2] + " " + tijdstrings[1] + " " 
										+ tijdstrings[5] + " " + tijdstrings[3] + " " + tijdstrings[4];
		tijd = tijd.toLowerCase();
		this.put("Date", tijd);
		
		
		
		//moet: thu, 25 aug 2002 13:17:03 gmt
		//is : Wed Sep 19 12:05:16 CEST 2007
	}
	
	public void setCODE(String code)
	{
		this.put("Code", code);
	}
	public void setREASON(String reason)
	{
		this.put("Reason", reason);
	}
	
	public void setBYTES(byte[] bytes)
	{
		this.body = bytes;
	}
	
	public void setType(String type)
	{	
		if(type.contains("html") || type.contains("htm"))
		{
			this.put("Content-Type", "text/html");
		}
		else if(type.contains("class"))
		{
			this.put("Content-Type", "application/x-java-applet");
		}
		else
		{
			this.put("Content-Type", "application/octet-stream");
		}
		
	}
	
	public void send()
	{
		String output =
		this.get("Version") + " " + this.get("Code") + " " + this.get("Reason") + "\n";
		this.remove("Version"); this.remove("Code"); this.remove("Reason");
		for (Iterator<String> headers = this.keySet().iterator(); headers.hasNext();){
			String h = headers.next();
			output += h + ": " + this.get(h) + "\n";
		}
		output += "Content-Length: " + body.length + "\n" +
		"\n";
		System.out.println("Sending response:\n\n"+output);
		String b = "";
		for (int i = 0; body.length > i; i++){
			b += (char) body[i];
		}
		System.out.println(b);
		try{
			OutputStream out = c.getOutputStream();
			out.write(output.getBytes());
			out.write(body);
		}catch (IOException ioe){
			
		}
	}
}
